package com.agileai.portal.portlets.bar;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletResponse;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;

import org.apache.pluto.container.PortletRequestContext;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.portal.bizmoduler.bar.ExtBarLinkManage;
import com.agileai.portal.bizmoduler.bar.ExtQueryBarConfigManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PortletVariableHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.driver.model.Page;
import com.agileai.portal.portlets.BaseMashupPortlet;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class ComplexSelecterPortlet extends BaseMashupPortlet {
	private static final String NEW_LINE = "\r\n";
	
	@SuppressWarnings("rawtypes")
	@RenderMode(name="view")
	public void view(RenderRequest request, RenderResponse response) throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String showYear = preferences.getValue("showYear", null);
		String showYearMonth = preferences.getValue("showYearMonth", null);
		String showYearQuarter = preferences.getValue("showYearQuarter", null);
		String showYearQuarterMonth = preferences.getValue("showYearQuarterMonth", null);
		String showDate = preferences.getValue("showDate", null);
		String onlyDate = preferences.getValue("onlyDate", null);
		
		String defaultShow = preferences.getValue("defaultShow", null);
		String redirectText = preferences.getValue("redirectText", "");
		String redirectURL = preferences.getValue("redirectURL", "");
		
		String isExtendBar = preferences.getValue("isExtendBar", "N");
		String isExtendLink = preferences.getValue("isExtendLink", "N");
		
		String isShowTimeRange = preferences.getValue("isShowTimeRange", "Y");
		String relativePosition = preferences.getValue("relativePosition", "after");
		String isOnlyOneLine = preferences.getValue("isOnlyOneLine", "Y");
		String isConvertText = preferences.getValue("isConvertText", "Y");
		String checkBoxValueSpliter = preferences.getValue("checkBoxValueSpliter", ";");
		String extendEnumDataURL = preferences.getValue("extendEnumDataURL", "");

		String defaultValueString = "&filterType="+defaultShow;
		String defaultVariableValues = preferences.getValue("defaultVariableValues",null);
		if (!StringUtil.isNullOrEmpty(defaultVariableValues)){
			defaultValueString = defaultValueString + "&"+defaultVariableValues;
		}
		PortletVariableHelper variableHelper = new PortletVariableHelper(request,defaultValueString);
		redirectURL = variableHelper.getRealDataURL(redirectURL);
		

		String isSetting = preferences.getValue("isSetting", null);
		String showList = "";
		String showListName = "";
		StringBuffer list = new StringBuffer();
		StringBuffer listName = new StringBuffer();
		if ("Y".equals(showYear)){
			list.append(",year");
			listName.append(",年");
		}
		
		if ("Y".equals(showYearMonth)){
			list.append(",yearMonth");
			listName.append(",年、月");
		}
		
		if ("Y".equals(showYearQuarter)){
			list.append(",yearQuarter");
			listName.append(",年、季度");
		}
		
		if ("Y".equals(showYearQuarterMonth)){
			list.append(",yearQuarterMonth");
			listName.append(",年、季度、月");
		}
		
		if ("Y".equals(showDate)){
			list.append(",date");
			listName.append(",时期段");
		}

		if ("Y".equals(onlyDate)){
			list.append(",onlyDate");
			listName.append(",指定日期");
		}
		
		if (list.toString().length() > 0){
			showList = list.toString().substring(1);
			showListName = listName.toString().substring(1);
		}

		PortletRequestContext requestContext = PortletRequestHelper.getRequestContext(request);
		Page page = (Page)requestContext.getAttribute(AttributeKeys.PAGE_KEY);
		
		String pageId = page.getPageId();
		String portletId = request.getWindowID();
		
		if ("Y".equals(isExtendBar)){
			ExtQueryBarConfigManage barConfigManage = (ExtQueryBarConfigManage)BeanFactory.instance().getBean("extQueryBarConfigManageService");
			DataParam param = new DataParam();
			param.put("pageId",pageId,"portletId",portletId);
			List<DataRow> barConfigRecords = barConfigManage.findRecords(param);
			HashMap<String,String> trigerCascadeMap = new HashMap<String,String>();
			trigerCascadeMap.put("trigerCascade","N");
			String extBarSyntax = this.buildExtendFormArea(barConfigRecords,response,trigerCascadeMap);
			request.setAttribute("extBarSyntax", extBarSyntax);

			String trigerCascade = trigerCascadeMap.get("trigerCascade");
			request.setAttribute("trigerCascade",trigerCascade);
		}
		
		HashMap filterMap = retreiveFilterMap(request);
		request.setAttribute("filerMap", filterMap);
		
		request.setAttribute("showYear", showYear);
		request.setAttribute("showYearMonth", showYearMonth);
		request.setAttribute("showYearQuarter", showYearQuarter);
		request.setAttribute("showYearQuarterMonth", showYearQuarterMonth);
		request.setAttribute("showDate", showDate);
		request.setAttribute("onlyDate", onlyDate);
		request.setAttribute("defaultShow", defaultShow);
		request.setAttribute("showList", showList);
		request.setAttribute("showListName", showListName);
		request.setAttribute("isSetting", isSetting);
		request.setAttribute("redirectText", redirectText);
		request.setAttribute("redirectURL", redirectURL);
		
		request.setAttribute("portletId",portletId);
		request.setAttribute("isExtendBar", isExtendBar);
		request.setAttribute("isExtendLink", isExtendLink);
		request.setAttribute("isShowTimeRange", isShowTimeRange);
		request.setAttribute("relativePosition", relativePosition);
		request.setAttribute("isOnlyOneLine", isOnlyOneLine);
		request.setAttribute("extendEnumDataURL", extendEnumDataURL);
		request.setAttribute("isConvertText", isConvertText);
		request.setAttribute("checkBoxValueSpliter", checkBoxValueSpliter);
		
		
		if ("Y".equals(isExtendLink)){
			ExtBarLinkManage extBarLinkManage = (ExtBarLinkManage)BeanFactory.instance().getBean("extBarLinkManageService");
			DataParam param = new DataParam();
			param.put("pageId",pageId,"portletId",portletId);
			List<DataRow> extBarLinkRecords = extBarLinkManage.findRecords(param);
			String extBarLinkSyntax = this.buildExtendLinkArea(extBarLinkRecords);
			request.setAttribute("extBarLinkSyntax", extBarLinkSyntax);
		}
		
		super.doView(request, response);
	}
	
	private String buildExtendFormArea(List<DataRow> barConfigRecords,PortletResponse response,HashMap<String,String> trigerCascadeMap){
		StringBuffer extBar = new StringBuffer();
		if (!ListUtil.isNullOrEmpty(barConfigRecords)){
			int count = barConfigRecords.size();
			String namespace = response.getNamespace();
			for (int i=0;i < count;i++){
				DataRow row = barConfigRecords.get(i);
				String code = row.stringValue("CODE");
				String name = row.stringValue("NAME");
				String fieldType = row.stringValue("FIELD_TYPE");
				String width = row.stringValue("DISPLAY_LENGTH");
				String breakLine = row.stringValue("BREAK_LINE");
				String trigerCascade = row.stringValue("TRIGER_CASCADE");
				
				if ("TEXT".equals(fieldType)){
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>").append(NEW_LINE);
					extBar.append("<label style='margin-right:3px'>").append(name).append("</label><input id='").append(code).append("' name='").append(code).append("' type='text' style='width:").append(width).append("px' value='' />").append(NEW_LINE);
					extBar.append("</span>").append(NEW_LINE);
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}
				}
				else if ("SELECT".equals(fieldType)){
					String onchangeHandler = "";
					if ("Y".equals(trigerCascade)){
						trigerCascadeMap.put("trigerCascade","Y");
						onchangeHandler = "doReloadQueryBar"+namespace+"();";
					}else{
						onchangeHandler = "doSearch"+namespace+"();";
					}
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>");
					extBar.append("<label style='margin-right:3px;'>").append(name).append("</label><select id='").append(code).append("' name='").append(code).append("' style='width:").append(width).append("px' onchange='").append(onchangeHandler).append("'></select>");
					extBar.append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}					
				}
				else if ("CHECKBOX".equals(fieldType)){
					extBar.append("<span style='margin:auto 5px;display:inline-block;' id='").append(code).append("Span'>");
					extBar.append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}					
				}
			}
		}
		return extBar.toString();
	}
	
	private String buildExtendLinkArea(List<DataRow> extBarLinkRecords){
		StringBuffer extBarLink = new StringBuffer();
		if (!ListUtil.isNullOrEmpty(extBarLinkRecords)){
			int count = extBarLinkRecords.size();
			for (int i=0;i < count;i++){
				DataRow row = extBarLinkRecords.get(i);
				String name = row.stringValue("NAME");
				String linkURL = row.stringValue("LINK_URL");
				String newPage = row.stringValue("NEW_PAGE");
				if ("N".equals(newPage)){
					extBarLink.append("<a hidefocus=\"true\" href=\"javascript:doLinkPortalPage('").append(linkURL).append("',false)\" class=\"button-link blue\">").append(name).append("</a>&nbsp;");
				}else{
					extBarLink.append("<a hidefocus=\"true\" href=\"javascript:doLinkPortalPage('").append(linkURL).append("',true)\" class=\"button-link blue\">").append(name).append("</a>&nbsp;");
				}
			}
		}
		return extBarLink.toString();
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private HashMap retreiveFilterMap(RenderRequest request){
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String namespace = getCurrentNamespace(request);
		String defaultShow = preferences.getValue("defaultShow", null);
		String defaultValueString = "namespace="+namespace+"&filterType="+defaultShow;
		String defaultVariableValues = preferences.getValue("defaultVariableValues",null);
		if (!StringUtil.isNullOrEmpty(defaultVariableValues)){
			defaultValueString = defaultValueString + "&"+defaultVariableValues;
		}
		PortletVariableHelper portletVariableHelper = new PortletVariableHelper(request,defaultValueString);
		HashMap result = new HashMap();
		result.put("filterType", portletVariableHelper.getRealValue("filterType"));
		result.put("year", portletVariableHelper.getRealValue("year"));
		result.put("quarter", portletVariableHelper.getRealValue("quarter"));
		result.put("month", portletVariableHelper.getRealValue("month"));
		result.put("dateFrom", portletVariableHelper.getRealValue("dateFrom"));
		result.put("dateTo", portletVariableHelper.getRealValue("dateTo"));
		result.put("selectedDate", portletVariableHelper.getRealValue("selectedDate"));
		return result;
	}
	
	@RenderMode(name="edit")
	public void edit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
	
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String showYear = preferences.getValue("showYear", null);
		String showYearMonth = preferences.getValue("showYearMonth", null);
		String showYearQuarter = preferences.getValue("showYearQuarter", null);
		String showYearQuarterMonth = preferences.getValue("showYearQuarterMonth", null);
		String showDate = preferences.getValue("showDate", null);
		String onlyDate = preferences.getValue("onlyDate", null);
		String defaultShow = preferences.getValue("defaultShow", null);
		String defaultVariableValues = preferences.getValue("defaultVariableValues", null);
		String isSetting = preferences.getValue("isSetting", null);
		
		String redirectText = preferences.getValue("redirectText", "");
		String redirectURL = preferences.getValue("redirectURL", "");
		
		String isExtendBar = preferences.getValue("isExtendBar", "N");
		String isExtendLink = preferences.getValue("isExtendLink", "N");
		
		String isShowTimeRange = preferences.getValue("isShowTimeRange", "Y");
		String relativePosition = preferences.getValue("relativePosition", "after");
		String isOnlyOneLine = preferences.getValue("isOnlyOneLine", "Y");
		String extendEnumDataURL = preferences.getValue("extendEnumDataURL", "");
		String isConvertText = preferences.getValue("isConvertText", "Y");
		String checkBoxValueSpliter = preferences.getValue("checkBoxValueSpliter", ";");
		
		request.setAttribute("showYear", showYear);
		request.setAttribute("showYearMonth", showYearMonth);
		request.setAttribute("showYearQuarter", showYearQuarter);
		request.setAttribute("showYearQuarterMonth", showYearQuarterMonth);
		request.setAttribute("showDate", showDate);
		request.setAttribute("onlyDate", onlyDate);
		request.setAttribute("defaultShow", defaultShow);
		request.setAttribute("defaultVariableValues", defaultVariableValues);
		request.setAttribute("isSetting", isSetting);
		
		request.setAttribute("redirectText", redirectText);
		request.setAttribute("redirectURL", redirectURL);
		
		request.setAttribute("isExtendBar", isExtendBar);
		request.setAttribute("isExtendLink", isExtendLink);
		request.setAttribute("isShowTimeRange", isShowTimeRange);
		request.setAttribute("relativePosition", relativePosition);
		request.setAttribute("isOnlyOneLine", isOnlyOneLine);
		request.setAttribute("extendEnumDataURL", extendEnumDataURL);
		request.setAttribute("isConvertText", isConvertText);
		request.setAttribute("checkBoxValueSpliter", checkBoxValueSpliter);
		
		PortletRequestContext requestContext = PortletRequestHelper.getRequestContext(request);
		Page page = (Page)requestContext.getAttribute(AttributeKeys.PAGE_KEY);
		
		String pageId = page.getPageId();
		String portletId = request.getWindowID();
		request.setAttribute("pageId", pageId);
		request.setAttribute("portletId", portletId);
		
		super.doEdit(request, response);
	}
	
	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException, IOException, PreferenceException {
		
		String showYear = request.getParameter("showYear");
		String showYearMonth = request.getParameter("showYearMonth");
		String showYearQuarter = request.getParameter("showYearQuarter");
		String showYearQuarterMonth = request.getParameter("showYearQuarterMonth");
		String showDate = request.getParameter("showDate");
		String onlyDate = request.getParameter("onlyDate");
		
		String defaultShow = request.getParameter("defaultShow");
		String defaultVariableValues = request.getParameter("defaultVariableValues");
		
		String redirectText = request.getParameter("redirectText");
		String redirectURL = request.getParameter("redirectURL");
		
		String isExtendBar = request.getParameter("isExtendBar");
		String isExtendLink = request.getParameter("isExtendLink");
		String isShowTimeRange = request.getParameter("isShowTimeRange");
		String relativePosition = request.getParameter("relativePosition");
		String isOnlyOneLine = request.getParameter("isOnlyOneLine");
		String extendEnumDataURL = request.getParameter("extendEnumDataURL");
		String isConvertText = request.getParameter("isConvertText");
		String checkBoxValueSpliter = request.getParameter("checkBoxValueSpliter");

		boolean isSetting = false;
		if (showYear == null){
			showYear = "N";
		}
		if (showYearMonth == null){
			showYearMonth = "N";
		}
		if (showYearQuarter == null){
			showYearQuarter = "N";
		}
		if (showYearQuarterMonth == null){
			showYearQuarterMonth = "N";
		}
		if (showDate == null){
			showDate = "N";
		}
		if (onlyDate == null){
			onlyDate = "N";
		}
		if ("N".equals(showYear) && "N".equals(showYearMonth) && 
			"N".equals(showYearQuarter) && "N".equals(showYearQuarterMonth) && "N".equals(showDate) && "N".equals(onlyDate)){
			isSetting = false;
		}else{
			isSetting = true;
		}
		
		PreferencesWrapper preferWrapper = new PreferencesWrapper();
		preferWrapper.setValue("showYear", showYear);
		preferWrapper.setValue("showYearMonth", showYearMonth);
		preferWrapper.setValue("showYearQuarter", showYearQuarter);
		preferWrapper.setValue("showYearQuarterMonth", showYearQuarterMonth);
		preferWrapper.setValue("showDate", showDate);
		preferWrapper.setValue("onlyDate", onlyDate);
		preferWrapper.setValue("defaultVariableValues", defaultVariableValues);
		preferWrapper.setValue("defaultShow", defaultShow);
		preferWrapper.setValue("redirectText", redirectText);
		preferWrapper.setValue("redirectURL", redirectURL);
		preferWrapper.setValue("isSetting", String.valueOf(isSetting));
		
		preferWrapper.setValue("isExtendBar", isExtendBar);
		preferWrapper.setValue("isExtendLink", isExtendLink);
		preferWrapper.setValue("isShowTimeRange", isShowTimeRange);
		preferWrapper.setValue("relativePosition", relativePosition);
		preferWrapper.setValue("isOnlyOneLine", isOnlyOneLine);
		preferWrapper.setValue("extendEnumDataURL", extendEnumDataURL);
		preferWrapper.setValue("isConvertText", isConvertText);
		preferWrapper.setValue("checkBoxValueSpliter", checkBoxValueSpliter);
		
		PreferencesHelper.savePublicPreferences(request, preferWrapper.getPreferences());
		response.setPortletMode(PortletMode.VIEW);
	}
	
	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
			String isCache = preferences.getValue("isCache", defaultIsCache);
			String dataURL = getDataURL(request,"extendEnumDataURL");
			ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
		} catch (Exception e) {
			this.logger.error("获取取数据失败getAjaxData", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
}